

package com.hazelcast.client.impl.protocol.codec.builtin;

import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.internal.serialization.impl.HeapData;

import static com.hazelcast.client.impl.protocol.ClientMessage.NULL_FRAME;
import static com.hazelcast.client.impl.protocol.codec.builtin.CodecUtil.nextFrameIsNullEndFrame;

public final class DataCodec {

    private DataCodec() {
    }

    public static void encode(ClientMessage clientMessage, Data data) {
        clientMessage.add(new ClientMessage.Frame(data.toByteArray()));
    }

    public static void encodeNullable(ClientMessage clientMessage, Data data) {
        if (data == null) {
            clientMessage.add(NULL_FRAME.copy());
        } else {
            clientMessage.add(new ClientMessage.Frame(data.toByteArray()));
        }
    }

    public static Data decode(ClientMessage.ForwardFrameIterator iterator) {
        return new HeapData(iterator.next().content);
    }

    public static Data decodeNullable(ClientMessage.ForwardFrameIterator iterator) {
        return nextFrameIsNullEndFrame(iterator) ? null : decode(iterator);
    }

}
